import React,{Component} from 'react';
import { View, Text, FlatList, StyleSheet, Dimensions, Image } from 'react-native';


class Home extends Component{

    // componentWillMount会在设置完state后，render前被调用执行
    componentWillMount(){
        // 请求数据
        fetch('http://47.100.185.180/api/list.php')
            .then((x)=>{
                this.setState({
                    list:JSON.parse(x._bodyInit)
                })
            })

    }

    constructor(){
        super();
        this.state={
            list:[
                {aid:'1111',title:'第一篇文章2',imgUrl:'http://bbs.houdunwang.com/data/attachment/block/75/75ef65965733aea55456cbf1c7a9280e.jpg'},
                {aid:'2222',title:'第2篇文章222',imgUrl:'http://bbs.houdunwang.com/data/attachment/block/75/75ef65965733aea55456cbf1c7a9280e.jpg'},
            ]
        }
    }

    // 用来处理每个data数据的函数
    _renderItem = ({item})=>(
        <View style={styles.item}>
            <Image source={{uri:item.imgUrl}} style={styles.itemimage}></Image>
            <Text style={styles.itemtitle}>{item.title}</Text>
        </View>

    )


    render() {
        return (
            <View>
                <Text>我是首页</Text>
                <FlatList
                    data={this.state.list}
                    renderItem={this._renderItem}
                    numColumns={2}
                    // 指定每个子元素的唯一的key
                    keyExtractor={(item)=>item.aid}
                />
            </View>
        )
    }
}




const styles = StyleSheet.create({

    item:{
        width:'50%',
        height:180,
        alignItems:'center'
    },
    itemimage:{
        width: Dimensions.get('window').width/2*0.8,
        height: Dimensions.get('window').width/2*0.8*9/16,
        // width:300,
        // height:200
    },
    itemtitle:{
        fontSize:16,
        marginTop:10,
        width:'80%'
    }
});

export default Home;


